package com.plan.base.exception;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.plan.base.constant.BaseCode;
import com.plan.base.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获处理
 *
 * @author zcl
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({HttpMessageNotReadableException.class,
            InvalidFormatException.class, NumberFormatException.class,
            MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class, MissingServletRequestParameterException.class})
    public Result<?> paramFormatExceptionHandle(Exception exception, HttpServletRequest request) {
        log.warn("参数错误", exception);
        return Result.fail(BaseCode.PARAM_ERROR).setMsg(Result.getMessages(BaseCode.PARAM_ERROR, request.getLocale()));
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Result<?> handle(Exception exception, HttpServletRequest request) {
        log.error("服务异常", exception);
        return Result.fail(BaseCode.SYS_ERROR).setMsg(Result.getMessages(BaseCode.SYS_ERROR, request.getLocale()));
    }

}